package com.example.java2mysql2.instrastructure;

import com.example.java2mysql2.domain.Student;
import com.example.java2mysql2.domain.StudentCondition;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Repository
public class UltraQueryer {
    @Resource
    private EntityManager entityManager;

    public List<Student> findDynamic(StudentCondition studentCondition){
        List<String> predicts = new ArrayList<>();
        if (!StringUtils.isEmpty(studentCondition.getStudentCode())){
            predicts.add("student_code like '%"+studentCondition.getStudentCode()+"%'");
        }
        if (!StringUtils.isEmpty(studentCondition.getStudentName())){
            predicts.add("student_name like '%"+studentCondition.getStudentName()+"%'");
        }
        if (!StringUtils.isEmpty(studentCondition.getTeamPosition())){
            predicts.add("team_position like '%"+studentCondition.getTeamPosition()+"%'");
        }
        String wh = predicts.stream().collect(Collectors.joining(" and "));
        System.out.println(wh);

       Query query =  entityManager.createNativeQuery("select * from student left join team on student.team_code = team.team_code where "+wh,Student.class);
       List<Student> ss = query.getResultList();
        System.out.println(ss);
        return ss;
    }
}
